package Client.GUI;

import Client.Net.*;
import Library.ErrorCodes;
import Library.Game.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.*;

/**
 *
 */
public class pnlGameList extends javax.swing.JPanel
{
    protected transient ICommunication m_Communication;
    protected transient List<IGameInfo> m_Games = new ArrayList<IGameInfo>();
    protected transient javax.swing.Timer m_Timer;
    
    /**
     * Creates new form pnlGameList
     * @param communication callback to frame and clientservice
     */
    public pnlGameList(ICommunication communication)
    {
        initComponents();
        setSize(getPreferredSize());
        m_Communication = communication;
        m_Timer = new javax.swing.Timer(1000, new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                try
                {
                    List<IGameInfo> games = m_Communication.getService().getGames();
                    int sIndex = lstGames.getSelectedIndex();
		    btnSelect.setEnabled(sIndex != -1);
                    DefaultListModel mdl = (DefaultListModel)lstGames.getModel();
                    mdl.clear();
                    if (games.isEmpty())
                    {
                        //m_Communication.log("WARNING: kan gamelijst niet opvragen.");
                        lblOpmerking.setText("No active games found\r\n");
                    }
                    else
                    {
                        Iterator<IGameInfo> it = games.iterator();
                        while (it.hasNext())
                        {
                            // Voeg GameServers to aan GameServer lijst in GUI.
                            IGameInfo game = it.next();
                            mdl.addElement(game.getName() + ":" + game.getPlayers() + "/" + game.getMaxPlayers());
                        }
                    }
                    lstGames.setSelectedIndex(sIndex);
		    btnSelect.setEnabled(sIndex != -1);
                }
                catch (Exception ex)
                {
                    m_Communication.logException(ex);
                }
                m_Timer.restart();
            }
        });
        m_Timer.start();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        lstGames = new javax.swing.JList();
        jLabel1 = new javax.swing.JLabel();
        btnCancel = new javax.swing.JButton();
        btnSelect = new javax.swing.JButton();
        btnCreate = new javax.swing.JButton();
        lblOpmerking = new javax.swing.JLabel();

        setPreferredSize(new java.awt.Dimension(460, 360));
        setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        lstGames.setModel(new javax.swing.DefaultListModel());
        lstGames.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                lstGamesValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(lstGames);

        jLabel1.setText("Game list, select a game");

        btnCancel.setText("Back");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        btnSelect.setText("Join");
        btnSelect.setEnabled(false);
        btnSelect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSelectActionPerformed(evt);
            }
        });

        btnCreate.setText("Create");
        btnCreate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCreateActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                            .addComponent(btnCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnSelect, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 376, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(btnCreate, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(lblOpmerking, javax.swing.GroupLayout.PREFERRED_SIZE, 376, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(34, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancel)
                    .addComponent(btnSelect))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnCreate)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 27, Short.MAX_VALUE)
                .addComponent(lblOpmerking, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 420, 320));
    }// </editor-fold>//GEN-END:initComponents

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        m_Timer.stop();
        m_Communication.SetContent(new pnlSelectServer(m_Communication));
}//GEN-LAST:event_btnCancelActionPerformed

    private void btnSelectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelectActionPerformed
        try
        {
            if(lstGames.getSelectedValue() != null)
            {
                String val = (String)lstGames.getSelectedValue();
                String[] parts = val.split(":");
                String game = parts[parts.length - 2];

                // Joinen van een game
                //TODO: error code ipv boolean
                int result = m_Communication.getService().joinGame(game);
                if (result != ErrorCodes.ERROR_NOERROR)
                {
		    JOptionPane.showMessageDialog(this, ErrorCodes.getMessage(result)); 
                    m_Communication.log("WARNING: Cannot join Game. Reason: " + ErrorCodes.getMessage(result));
                    //TODO: dispose en unexport
                }
                else
                {
                   //TODO: Handel deze regel af vanuit framework en dan automatisch bij frame swapping!
                   lblOpmerking.setText("Joined Game. " + ErrorCodes.getMessage(result) + "\r\n");
                   m_Timer.stop();
                   
                   pnlLobby lobby = new pnlLobby(m_Communication, false);
                   m_Communication.SetContent(lobby);
                }
            }
	    //else
	    //{
		// Geen Null-namen van games joinen, following commented
		//int·result·=·m_Communication.getService().joinGame(null);
		//JOptionPane.showMessageDialog(this, ErrorCodes.getMessage(result)); 
	    //}
        }
        catch (Exception ex)
        {
            m_Communication.logException(ex);
        }
}//GEN-LAST:event_btnSelectActionPerformed

    private void btnCreateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCreateActionPerformed
        m_Communication.SetContent(new pnlCreateGame(m_Communication));
    }//GEN-LAST:event_btnCreateActionPerformed

    private void lstGamesValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_lstGamesValueChanged
        btnSelect.setEnabled(lstGames.getSelectedIndex() >= 0);
    }//GEN-LAST:event_lstGamesValueChanged


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnCreate;
    private javax.swing.JButton btnSelect;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblOpmerking;
    private javax.swing.JList lstGames;
    // End of variables declaration//GEN-END:variables
}
